import { ProChat } from '@ant-design/pro-chat';
import { useModel } from '@umijs/max';
import { useTheme } from 'antd-style';
import { chatCompletion, streamChat } from '@/services/swagger/chatController';
export async function streamChatCustom(body: API.ChatCompletionQuery) {
  // 直接返回fetch的Promise（原生Response对象）
  return fetch('/api/chat/completion', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      // 如有需要，添加认证头
      // "Authorization": `Bearer ${token}`,
    },
    body: JSON.stringify(body),
  });
}
export default () => {
  const theme = useTheme();
  const { initialState } = useModel('@@initialState');

  async function getResponse(messages: any[]) {
    let requestMessage = '';
    console.log(messages);
    messages.forEach((item) => {
      requestMessage += item.message;
    });
    const response = await chatCompletion({
      message: requestMessage,
      userId: initialState?.currentUser?.id,
    });
    return new Response(response);
  }

  return (
    <div style={{ background: theme.colorBgLayout }}>
      <ProChat
        style={{ height: 600 }}
        helloMessage={
          '欢迎使用 ProChat ，我是你的\n\n专属机器人，这是我们的 Github：[ProChat](https://github.com/ant-design/pro-chat)'
        }
        request={async (messages: any) => {
          console.log('messages', messages);
          const response = await streamChatCustom({
            message: messages[messages.length - 1].content,
            userId: initialState?.currentUser?.id,
          });
          console.log('response', response);

          if (!response.ok || !response.body) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          const reader = response.body.getReader();
          const decoder = new TextDecoder('utf-8');
          const encoder = new TextEncoder();

          const readableStream = new ReadableStream({
            async start(controller) {
              let leftover = '';
              let lastWasWord = false;

              function push() {
                reader
                  .read()
                  .then(({ done, value }) => {
                    if (done) {
                      if (leftover) {
                        const cleaned = leftover
                          .replace(/^data:\s*/, '')
                          .replace(/data:\s*/g, '');
                        if (cleaned) {
                          controller.enqueue(encoder.encode(cleaned));
                        }
                      }
                      controller.close();
                      return;
                    }

                    const chunk = decoder.decode(value, { stream: true });
                    const fullChunk = leftover + chunk;
                    const parts = fullChunk.split(/(?:\r?\n){2,}/);
                    leftover = parts.pop() || '';

                    parts.forEach((part) => {
                      if (part) {
                        let content = part
                          .replace(/^data:\s*/, '')
                          .replace(/data:\s*/g, '');
                        if (content) {
                          // 单词空格逻辑
                          const isWord = /^[a-zA-Z]+$/.test(content);
                          const isPunctuation = /^[!.,?;:)]+$/.test(content);
                          const isStartWithCapital = /^[A-Z]/.test(content);

                          if (isWord) {
                            if (lastWasWord && !isStartWithCapital) {
                              content = ' ' + content;
                            }
                            lastWasWord = true;
                          } else if (isPunctuation) {
                            lastWasWord = false;
                          } else {
                            if (lastWasWord) {
                              content = ' ' + content;
                            }
                            lastWasWord = false;
                          }
                          controller.enqueue(encoder.encode(content));
                        }
                      }
                      controller.enqueue(encoder.encode('\n\n'));
                    });

                    push();
                  })
                  .catch((err) => {
                    console.error('读取流中的数据时发生错误', err);
                    controller.error(err);
                  });
              }

              push();
            },
          });

          return new Response(readableStream);
        }}
      />
    </div>
  );
};
